package netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import netty.codec.UnixTime;

import java.util.Date;

@Slf4j
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * Creates a client-side handler.
     */
    public TimeClientHandler() {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("receive data 1: {}", msg);
        if (msg instanceof ByteBuf) {
            final ByteBuf byteBuf = (ByteBuf) msg;
            final long time = byteBuf.readLong();
            byteBuf.release();

            final ByteBuf sendDataBuf = Unpooled.copyLong(System.currentTimeMillis());
            log.info("receive data 2: {}", new Date(time));
            ctx.writeAndFlush(sendDataBuf).addListener(ChannelFutureListener.CLOSE);
//            ctx.close();
        }

        if (msg instanceof UnixTime) {
            UnixTime time = (UnixTime)msg;
            log.info("receive data time: {}", time);

            ctx.writeAndFlush(new UnixTime(System.currentTimeMillis())).addListener(ChannelFutureListener.CLOSE);
            // ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
